<script setup>

import {userStore} from "@/stores/userStore.js";
import MyTable from "@/components/constant/myTable.vue";
import {
  addUser, banUser,
  delUser, empower,
  getUserList, getUserPowerList, getUserRoleList,
  resetPsd,
  updateUser
} from "@/api/httpApi/userApi.js";
import {successCode} from "@/api/httpApi/base/http.js";
import {onMounted, ref, watch} from "vue";
import {constantStore} from "@/stores/constantStore.js";
import {error, success} from "@/api/myMessage.js";
import MsgSubmit from "@/components/constant/msgSubmit.vue";

const userTag = ref([])
/**
 * 初始化相关
 */
let userMapping = ref([
  {
    label: "ID",
    prop: "id",
    propConfig: {
      align: "center",
      width: "180",
      type: "text",
    },
  },
  {
    label: "用户名",//表头名称 必填
    prop: "name",//数据对应字段 必填
    propConfig: {
      align: "center",//对齐方式 非必填 不写默认左对齐
      type: "text",// 非必填 不写默认text   text(文本) selectText(根据给定列表，选择内容)  tag(标签)  Switch(开关)  image(图片)
      fixed: 'left',//固定列的位置
    },
    editHandle: userStore().root ? "add_update" : "",//出现在编辑中的操作 必填  添加有  修改有，
    editTypeConfig: {
      editProp: "name",// 编辑框的数据字段名称  非必填 不写默认用prop
      labelWidth: "100",
      required: true,//是否必传，默认false
      editType: "text", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      editTextType: "text",
      rules: []//构建默认的校验规则
    }
  },
  {
    label: "游戏名",//表头名称 必填
    prop: "gameName",//数据对应字段 必填
    propConfig: {
      align: "center",//对齐方式 非必填 不写默认左对齐
      type: "text",// 非必填 不写默认text   text(文本) selectText(根据给定列表，选择内容)  tag(标签)  Switch(开关)  image(图片)
      fixed: 'left',//固定列的位置
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有  修改有，
    editTypeConfig: {
      editProp: "name",// 编辑框的数据字段名称  非必填 不写默认用prop
      labelWidth: "100",
      required: true,//是否必传，默认false
      editType: "text", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      editTextType: "text",
    }
  },
  {
    label: "会员等级",
    prop: "roleName",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editHandle: userStore().root ? "add_update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "select",
      option: userStore().powerTable,//选择框选项
    },
  },
  {
    label: "权限等级",
    prop: "powerNumber",
    propConfig: {
      align: "center",
      width: "120",
      type: "tag",
      stateMapping: userStore().powerTableOption
    },
    editHandle: userStore().root ? "add_update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      // editProp: "power",// 编辑框的数据字段名称  非必填 不写默认用prop
      labelWidth: "100",
      editType: "select",
      option: userStore().powerTable,//选择框选项
    },
  },
  {
    label: "当前折扣",
    prop: "discount",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editTypeConfig: {
      labelWidth: "100",
      editType: "text",
      editTextType: "number"
    },
  },
  {
    label: "描 述",
    prop: "description",
    propConfig: {
      align: "center",
      width: "200",
      type: "text",
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有  修改有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      editTextType: "text"
    }
  },
  {
    label: "头像",
    prop: "image",
    propConfig: {
      align: "center",
      width: "200",
      type: "image",
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有  修改有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "image", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      imageConfig: {
        radius: 0,
        size: "200",//单位PX 有size配置，  width 和height 将会失效 且 shape等于circle，仅仅会生效此属性
        fit: "cover", //图片如何适应到容器框，同原生 object-fit。  'fill', 'contain', 'cover', 'none', 'scale-down',
        lazy: true,
        alt: "热门图标",
      },
      cropperConfig: {
        canScale: true,//图片是否允许滚轮缩放 默认true
        autoCrop: true,//是否默认生成截图框 默认false
        fixed: false,//是否开启截图框宽高固定比例 默认false
        fixedNumber: [1, 1],//截图框的宽高比例, 开启fixed生效 默认[1, 1]  ([ 宽度 , 高度 ])
        full: false,//是否输出原图比例的截图, 默认false
        canMove: true,//上传图片是否可以移动, 默认true
        canMoveBox: false,//截图框能否拖动, 默认true
        original: false,//上传图片按照原始比例渲染, 默认false
        centerBox: false,//截图框是否被限制在图片里面 默认false
        high: true,//是否按照设备的dpr输出等比例图片 默认true
        infoTrue: false,//true 为展示真实输出图片宽高 默认false 展示看到的截图框宽高
        fixedBox: true,//固定截图框大小, 不允许改变 默认false false
      },
    }
  },
  {
    label: "邮箱",
    prop: "email",
    propConfig: {
      align: "center",
      width: "200",
      type: "text",
    },
    editHandle: userStore().root ? "add_update" : "",//出现在编辑中的操作 必填  添加有  修改有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text"
    }
  },
  {
    label: "电话",
    prop: "phone",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text",
      editTextType: "number"
    },
  },
  {
    label: "用户状态",
    prop: "state",
    propConfig: {
      align: "center",
      width: "120",
      type: "tag",
      stateMapping: [
        {type: "success", data: "0", msg: "正常"},
        {type: "warring", data: "1", msg: "注销"},
        {type: "danger", data: "2", msg: "封禁"}
      ]
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      editType: "select", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      labelWidth: "100",
      option: [
        {
          label: "正常",
          value: "0"
        },
        {
          label: "注销",
          value: "1"
        },
        {
          label: "封禁",
          value: "2"
        }
      ],//选择框选项
    },
  },
  {
    label: "新人奖励状态",
    prop: "isGet",
    propConfig: {
      align: "center",
      width: "120",
      type: "tag",
      stateMapping: [
        {type: "success", data: "1", msg: "领 取"},
        {type: "danger", data: "0", msg: "未领取"}
      ]
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      editProp: "receiveState",
      editType: "select", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      labelWidth: "100",
      option: [
        {
          label: "未领取",
          value: "0"
        },
        {
          label: "领 取",
          value: "1"
        }
      ],//选择框选项
    },
  },
  {
    label: "性别",
    prop: "sex",
    propConfig: {
      align: "center",
      width: "120",
      type: "tag",
      stateMapping: [
        {type: "primary", data: "0", msg: "男"},
        {type: "warring", data: "1", msg: "女"},
        {type: "danger", data: null, msg: "未知"}
      ]
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      editType: "select", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      labelWidth: "100",
      option: [
        {
          label: "男",
          value: "0"
        },
        {
          label: "女",
          value: "1"
        },
        {
          label: "未知",
          value: null
        }
      ],//选择框选项
    },
  },
  {
    label: "SteamId",
    prop: "steamId",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text",
      editTextType: "number"
    },
  },
  {
    label: "游戏ID",
    prop: "gameId",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text",
      editTextType: "number"
    },
  },
  {
    label: "QQ号",
    prop: "qq",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text",
      editTextType: "number"
    },
  },
  {
    label: "账户余额",
    prop: "money",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有，
    editTypeConfig: {
      labelWidth: "100",
      editType: "text",
      editTextType: "number"
    },
  },
  {
    label: "累计消费",
    prop: "amount",
    propConfig: {
      align: "center",
      width: "120",
      type: "text"
    }
  },
  {
    label: "个人简介",
    prop: "introduction",
    propConfig: {
      align: "center",
      width: "200",
      type: "text"
    }
  },
  {
    label: "邀请码",
    prop: "invitationCode",
    propConfig: {
      align: "center",
      width: "200",
      type: "text"
    }
  },
  {
    label: "邀请人",
    prop: "invitationUserId",
    propConfig: {
      align: "center",
      width: "200",
      type: "tag",
      stateMapping: userTag
    }
  },
  {
    label: "收货地址",
    prop: "introduction",
    propConfig: {
      align: "center",
      width: "200",
      type: "text"
    }
  },
  {
    label: "创建时间",
    prop: "createTime",
    propConfig: {
      align: "center",
      width: "200",
      type: "text",
    },
  },
  {
    label: "最近修改时间",
    prop: "updateTime",
    propConfig: {
      align: "center",
      width: "200",
      type: "text",
    },
  },
  {
    label: "备 注",
    prop: "remarks",
    propConfig: {
      align: "center",
      width: "400",
      type: "text",
    },
    editHandle: userStore().root ? "update" : "",//出现在编辑中的操作 必填  添加有  修改有，
    editTypeConfig: {
      editType: "text", //编辑框类型，非必填 默认text 文本类型  支持图片类型（image） 选择框（select），
      editTextType: "text",
      require: true,
      labelWidth: "100"
    },
  },
])
onMounted(() => {
  initUserList();
  initUserOtherList();
})

let userList = ref()

function initUserList() {
  getUserList(pageObj.value.currentPage, pageObj.value.pageSize, searchObject.value).then(res => {
        if (successCode === res.code) {
          userList.value = res.data.content;
          constantStore().copyPage(pageObj, res.data);
          userTag.value = constantStore().listToTag(res.data.content, "name", "id");
        }
      }
  )
}

let userRoleList = ref([])
let userRoleSelect = ref([])

let userPowerList = ref([])
let userPowerSelect = ref([])

function initUserOtherList() {
  getUserRoleList().then(res => {
    if (res.code === successCode) {
      userRoleList.value = res.data;
      if (userRoleList.value && userRoleList.value.length >= 1) {
        userRoleSelect.value = [];
        userRoleSelect.value = constantStore().listToSelect(userPowerList.value, "name", "id");
      }
    }
  })

  getUserPowerList().then(res => {
    if (res.code === successCode) {
      userPowerList.value = res.data;
      if (userPowerList.value && userPowerList.value.length >= 1) {
        userPowerSelect.value = [];
        userPowerSelect.value = constantStore().listToSelect(userPowerList.value, "name", "id");
      }
    }
  })
}

/**
 * 搜索相关
 */
let searchObject = ref({
  userKey: "",
  roleId: "",
  powerId: "",
  moneyMin: "",
  moneyMax: "",
  amountMin: "",
  amountMax: ""
})

function keySearch() {

}

function doSearch() {
  initUserList()
}

function clearSearch() {
  searchObject.value = {
    userKey: "",
    roleId: "",
    powerId: "",
    moneyMin: "",
    moneyMax: "",
    amountMin: "",
    amountMax: ""
  }
}

/**
 * 分页相关
 */
let pageObj = ref({
  currentPage: 1,
  pageSize: 10,
  totalPages: 10,
  totalCount: 1,
  first: false,
  last: false,
})

function handleSizeChange() {
  initUserList();
}

function handleCurrentChange() {
  initUserList();
}

/**
 * 其他相关
 */
let resetPasswordDisabled = ref(false)
let thisUserId = ref("")

function resetPassword(index, item) {
  thisUserId.value = item.id;

}

function cancelPassword() {
  thisUserId.value = item.id;

}

function doResetPassword(userId) {
  resetPsd().then(userId, userId).then(res => {
  })
}

let setPowerBtnDisable = ref(false)

function setPower(index, item) {
  thisUserId.value = item.id;
  setPowerBtnDisable.value = true;
  empower(thisUserId.value).then(res => {
    setPowerBtnDisable.value = false;
    if (successCode === res.code) {
      initUserList();
      success(res.message);
    } else {
      error(res.message);
    }
  })
}

let banUserDisabled = ref(false)

function banThisUser(index, item) {
  banUserDisabled.value = true;
  thisUserId.value = item.id;
  banUser(thisUserId.value).then(res => {
    banUserDisabled.value = false;
    if (successCode === res.code) {
      initUserList();
      success(res.message);
    } else {
      error(res.message);
    }
  })
}

function isNoPower(item) {
  return userStore().isUser(item.powerNumber);
}

function isNoBan(item) {
  return userStore().admin && userStore().isHighPower(item.powerNumber);
}

let sendAllEmailDisabled = ref(false)

function sendAllEmail() {
  sendEmailBefore();
}

let sendOneEmailDisabled = ref(true)

function sendOneEmail(index, item) {
  emailObj.value.toUserId = item.id;
  sendEmailBefore();
}

let emailObj = ref({
  title: null,
  msg: null,
  fromUserId: null,
  toUserId: null,
})
let emailBoxShow = ref(false)

function sendEmailBefore() {
  emailBoxShow.value = true;
}

watch(() => emailObj.value.msg, (newVal) => {
})

function doSendEmail() {

}
</script>

<template>
  <div id="user-info-box" class="user-info-box">
    <div class="user-info-btn">

    </div>
    <div class="user-info-center">
      <my-table :dataList="userList"
                @after-edit="initUserList"
                :addAction="(user) => { return addUser(user)}"
                :updateAction="(user) => { return updateUser(user)}"
                :delAction="(ids) => { return delUser(ids)}"
                title="用户"
                :has-page="true"
                :btn-config="{add: userStore().root,update: true,del: userStore().root}"
                :edit-btn-width="440"
                :mapping="userMapping">
        <template #buttonAdd>
          <div class="button-box-item">
            <el-button type="primary" @click="sendAllEmail" disabled>群发邮件</el-button>
          </div>
          <div class="button-box-item input-box">
            <el-input clearable v-model="searchObject.userKey" placeholder="请输入搜索用户名(游戏名/steamId/QQ号)"
                      @keydown.enter="keySearch"></el-input>
          </div>
          <div class="button-box-item" style="width: 20rem">
            <el-select v-model="searchObject.powerId" placeholder="请选择权限等级" clearable>
              <el-option v-for="(item,index) in userPowerSelect" :key="index"
                         :label="item.label" :value="String(item.value)"/>
            </el-select>
          </div>
          <div v-if="userRoleSelect.length > 1" class="button-box-item" style="width: 20rem">
            <el-select v-model="searchObject.roleId" placeholder="请选择会员等级" clearable>
              <el-option v-for="(item,index) in userRoleSelect" :key="index"
                         :label="item.label" :value="String(item.value)"/>
            </el-select>
          </div>
          <div class="button-box-item money-box">
            <div class="search-money-title">
              余额
            </div>
            <div class="search-money-range">
              <div class="money-range-min">
                <el-input clearable v-model="searchObject.moneyMin" type="number" placeholder="最小值"></el-input>
              </div>
              &nbsp;-&nbsp;
              <div class="money-range-max">
                <el-input clearable v-model="searchObject.moneyMax" type="number" placeholder="最大值"></el-input>
              </div>
            </div>
          </div>
          <div class="button-box-item money-box">
            <div class="search-money-title">
              累计消费金额
            </div>
            <div class="search-money-range">
              <div class="money-range-min">
                <el-input clearable v-model="searchObject.amountMin" type="number" placeholder="最小值"></el-input>
              </div>
              &nbsp;-&nbsp;
              <div class="money-range-max">
                <el-input clearable v-model="searchObject.amountMax" type="number" placeholder="最大值"></el-input>
              </div>
            </div>
          </div>
          <div class="button-box-item">
            <el-button type="primary" @click="doSearch">搜 索</el-button>
            <el-button type="primary" @click="clearSearch">清 空</el-button>
          </div>
        </template>
        <template #tableBtnAdd="scope">
          <el-button size="small" type="primary" :disabled="resetPasswordDisabled"
                     @click="resetPassword(scope.index,scope.row)">重置密码
          </el-button>
          <el-button size="small" type="danger" :disabled="banUserDisabled" v-if="isNoBan(scope.row)"
                     @click="banThisUser(scope.index,scope.row)">封 禁
          </el-button>
          <el-button size="small" type="primary" :disabled="sendOneEmailDisabled"
                     @click="sendOneEmail(scope.index,scope.row)">发送邮件
          </el-button>
          <el-button v-if="isNoPower(scope.row)" size="small" type="success" :disabled="setPowerBtnDisable"
                     @click="setPower(scope.index,scope.row)">授 权
          </el-button>
        </template>
        <template #page>
          <el-pagination
              v-model:current-page="pageObj.currentPage"
              v-model:page-size="pageObj.pageSize"
              :page-sizes="constantStore().pageSizes"
              :small="false"
              :disabled="false"
              :background="false"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageObj.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
        </template>
      </my-table>
    </div>
    <div class="user-dialog-box">
      <div class="send-email-dialog">
        <msg-submit v-model:msg="emailObj.msg" v-model:show="emailBoxShow"></msg-submit>
      </div>
      <div class="restart-psd-dialog">

      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">

#user-info-box {

  .input-box {
    width: 30rem;
  }

  .money-box {
    display: flex;
    flex-direction: column;
    width: 40rem;
    height: 6rem;

    .search-money-title {
      margin: 0 auto;
    }

    .search-money-range {
      display: flex;
    }
  }
}

</style>